﻿using System;
using System.Web.UI;

namespace PD.Web.DynamicData.FieldTemplates
{
    /// <summary>
    /// Represents the children field template control.
    /// </summary>
    public partial class ChildrenField : System.Web.DynamicData.FieldTemplateUserControl
    {
        /// <summary>
        /// A value indicating whether a navigation to the children element is allowed.
        /// </summary>
        private bool allowNavigation = true;

        /// <summary>
        /// The navigate URL.
        /// </summary>
        private string navigateUrl;

        /// <summary>
        /// Gets or sets the navigate URL.
        /// </summary>
        /// <value>
        /// The navigate URL.
        /// </value>
        public string NavigateUrl
        {
            get
            {
                return this.navigateUrl;
            }

            set
            {
                this.navigateUrl = value;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether a navigation to the children element is allowed.
        /// </summary>
        /// <value>
        ///   <c>true</c> if a navigation to the children element is allowed; otherwise, <c>false</c>.
        /// </value>
        public bool AllowNavigation
        {
            get
            {
                return this.allowNavigation;
            }

            set
            {
                this.allowNavigation = value;
            }
        }

        /// <summary>
        /// Gets the data control that handles the data field in a field template.
        /// </summary>
        /// <returns>A data control that handles the data field in a field template.</returns>
        public override Control DataControl
        {
            get
            {
                return this.HyperLink1;
            }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.HyperLink1.Text = "View " + this.ChildrenColumn.ChildTable.DisplayName;
        }

        /// <summary>
        /// Gets the children path.
        /// </summary>
        /// <returns>
        /// The children path.
        /// </returns>
        protected string GetChildrenPath()
        {
            if (!this.AllowNavigation)
            {
                return null;
            }

            if (string.IsNullOrEmpty(this.NavigateUrl))
            {
                return this.ChildrenPath;
            }
            else
            {
                return this.BuildChildrenPath(this.NavigateUrl);
            }
        }
    }
}
